package org.example.aitest.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpClientUploader {

    /**
     * 上传文件到指定URL
     *
     * @param url      上传地址
     * @param files    文件Map，key为表单字段名，value为文件对象
     * @param params   其他表单参数
     * @return 服务器响应内容
     * @throws IOException
     */
    public static String upload(String url, Map<String, File> files, Map<String, String> params) throws IOException {

        HttpRequestRetryHandler retryHandler = (exception, executionCount, context) -> {
            if (executionCount >= 3) {
                return false; // 最多重试3次
            }
            if (exception instanceof SocketException) {
                return true; // 对SocketException重试
            }
            return false;
        };

        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(5000)
                .setSocketTimeout(15000)
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setRetryHandler(retryHandler)
                .setDefaultRequestConfig(config)
                .build();
        HttpPost httpPost = new HttpPost(url);

        // 构建多部分实体
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        
        // 添加文件参数
        if (files != null && !files.isEmpty()) {
            for (Map.Entry<String, File> entry : files.entrySet()) {
                FileBody fileBody = new FileBody(entry.getValue());
                builder.addPart(entry.getKey(), fileBody);
            }
        }
        
        // 添加普通表单参数
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                StringBody stringBody = new StringBody(entry.getValue(), 
                    ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8));
                builder.addPart(entry.getKey(), stringBody);
            }
        }
        
        HttpEntity multipart = builder.build();
        httpPost.setEntity(multipart);

        httpPost.setHeader("Authorization", "Bearer sk-06daae4607c0459295ccd4db313f9719");
        
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity responseEntity = response.getEntity();
            return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
        } finally {
            httpClient.close();
        }
    }
}